package com.handong.handserialprogram.threadpool;


import android.util.Log;
import android.view.View;

import com.handong.handserialprogram.utils.CheckUtil;
import com.handong.handserialprogram.utils.SPUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

import cn.pda.serialport.SerialPort;
import cn.pda.serialport.Tools;

public class FindRingsThread implements Runnable {
    private String TAG = "FindRingsThread";
    private InputStream mReadStream;
    private SerialPort mSerialPort;
    private OutputStream mWriteStream;

    private int sendTime = 0;
    private Boolean isStopPush = true;
    private int funCode = 0;

    @Override
    public void run() {
        try {
            doWork();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public FindRingsThread(Integer tag) {
        this.funCode = tag;

    }
    public void setBoolean(Boolean isStopPush){
        this.isStopPush = isStopPush;
    };
    private void doWork() throws IOException {
        mSerialPort = new SerialPort();
        mSerialPort.rfid_poweron();

        this.mSerialPort.openSerial(13, 115200);

        if ((mReadStream == null) || (mWriteStream == null)) {

            mReadStream = mSerialPort.getInputStream();
            mWriteStream = mSerialPort.getOutputStream();
        }

        while (isStopPush) {
            sendTime++;
            byte[] sendData = getSendStr();
            Log.d(TAG, "发送命令：" + Arrays.toString(sendData));
            try {
                Log.d(TAG, "发送次数：" + sendTime);
                Thread.sleep(1000);
                mWriteStream.write(sendData);
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
                Log.d(TAG, "循环发送命令" + Tools.byteToHexString(sendData) + "。");
            }
        }
    }

    private byte[] getSendStr() {
        StringBuilder result = new StringBuilder("7577");

        result.append(Tools.intToHexString(funCode));
        if (funCode == 1) {
            result.append(Tools.intToHexString(2));
            result.append(SPUtil.getStringValue(SPUtil.IMEI_CRC));
        }
//        if (funCode == 4) {
//            String[] id = ids.split(",");
//            result.append(Tools.intToHexString(id.length * 2));
//            for (int i = 0; i < id.length; i++) {
//                result.append(id[i]);
//            }
//        }
        byte[] resultStr = CheckUtil.checkSum8Caculation(result.toString());
        return resultStr;
    }


}
